package com.example.testing.ipcdemo.Socket;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

/**
 * Created by tangjiangxu on 9/14/17.
 */

public class TCPServerService extends Service {
    private static final String TAG = "TCPServerService";

    private boolean mIsServiceDestoryed = false;
    private String[] mDefinedMessage = new String[] {
        "你好啊，哈哈！",
            "请问你叫什么名字啊？",
            "今天上海的天气怎么演噶？",
            "你知道吗？我可是可以和多个人同事聊天的喔",
            "给你讲个笑话把，爱笑的人的运气一定不会太差"
    };

    @Override
    public void onCreate() {
        Log.e(TAG, "onCreate: ");
        super.onCreate();
        new Thread(new TcpServer()).start();
    }

    private class TcpServer implements Runnable {

        @Override
        public void run() {
            ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(8688);
            } catch (IOException e) {
                e.printStackTrace();
            }

            while (!mIsServiceDestoryed) {
                //接收客户端的请求

                try {
                    final Socket client = serverSocket.accept();
                    Log.e(TAG, "run: accept");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            responseClient(client);
                        }
                    }).start();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    private void responseClient(Socket client) {
        try {
            //用于接收客户端的消息
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            //用于向客户端发送消息
            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
            out.print("欢迎来到聊天室！");
            while (!mIsServiceDestoryed) {
                String str = in.readLine();
                Log.e(TAG, "responseClient: msg form client:" + str);
                if (str == null) {
                    //客户端断开连接
                    break;
                }
                int i = new Random().nextInt(mDefinedMessage.length);
                String msg = mDefinedMessage[i];
                out.println(msg);
                Log.e(TAG, "responseClient: send:" + msg);
            }

            in.close();
            out.close();
            client.close();
            Log.e(TAG, "responseClient: client quit");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mIsServiceDestoryed = true;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
